package com.asiainfo.integration.queue;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.*;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;

/**
 * Usage:
 *
 * @author Charkey
 * @date 4/1/2016
 */
public class Samples {

    public static void main(String[] args) {
        new Samples().readXml();
    }

    public void readXml() {
        try {
            URL url = this.getClass().getClassLoader().getResource("config/queue/queue-details.xml");
            SAXReader reader = new SAXReader();
            InputStream in = new FileInputStream(new File(url.toURI().getPath()));
            Document document = reader.read(in);

            Element root = document.getRootElement();
            List<Element> elements = root.elements();
            for (Element element : elements) {
                System.out.println(element.element("interfaceName").getText());
                System.out.println(element.element("initialContextFactory").getText());
                System.out.println(element.element("connectionUrl").getText());
                System.out.println(element.element("connectionFactory").getText());
                System.out.println(element.element("queueName").getText());
                System.out.println(element.element("username").getText());
                System.out.println(element.element("password").getText());
            }

            document.asXML();

            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(url.toURI().getPath())), format);
            writer.write(document);
            writer.flush();
            writer.close();

        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

    }
}
